
using System;
using System.Data;
using System.Data.SqlClient;

namespace gtksharpdb
{

	public class MonoMSSql : IDBFunction
	{
		private DBStatic dbs;
		private SqlConnection sqlconn;
		
		public MonoMSSql (DBStatic mssqldbpapameters)
		{
			dbs = mssqldbpapameters;
		}
		
		#region IDBFunction implementation
		
		//Establish MS SQL connection
		public int DBConnection ()
		{
			string connstring = "Server="+dbs.dbserver+";Database="+dbs.dbname+";User ID="+dbs.dbuser+";Password="+dbs.dbpin+""; 
			try
			{
				sqlconn = new SqlConnection(connstring);
				sqlconn.Open();
				return 1;
			}
			catch (Exception ex)
			{
				ErrorHandler(ex);
				return -1;
			}
			
		}
		
		//Close connection
		public void DBClose ()
		{
			if(sqlconn.State == System.Data.ConnectionState.Open)
			{
				sqlconn.Close();
			}
		}
		
		//Return query in DataSet
		public DataSet DBQueryDS (string query)
		{
			try {
				DataSet ds = new DataSet();
				SqlDataAdapter da = new SqlDataAdapter(query, sqlconn);
				da.Fill(ds);
				
				return ds;
			} 
			catch (Exception ex)
			{
				ErrorHandler(ex);
				return null;
			}
		}
		
		//Return query in DataReader
		public IDataReader DBQueryDR (string query)
		{
			try {
				SqlCommand cmd = new SqlCommand(query, sqlconn);
				SqlDataReader dr = cmd.ExecuteReader();
				
				return dr;
			} 
			catch (Exception ex)
			{
				ErrorHandler(ex);
				return null;
			}		
			
		}
		
		//Execute non-query command
		public int DBCommand (string command)
		{
			try
			{
				SqlCommand cmd = new SqlCommand(command, sqlconn);
				int i =  cmd.ExecuteNonQuery();
				return i;
			}
			catch (Exception ex)
			{
				ErrorHandler(ex);
				return -1;
			}
		}

		public void ErrorHandler (Exception ex)
		{
			throw new System.NotImplementedException();
		}
		
		#endregion

	}
}
